<template>
  <div class="nutrition-stats-container">
    <div class="stats-header">
      <div class="header-title">营养摄入统计</div>
      <div class="time-range-selector">
        <van-dropdown-menu>
          <van-dropdown-item v-model="timeRange" :options="timeRangeOptions" />
        </van-dropdown-menu>
      </div>
    </div>

    <div class="nutrition-chart-container" v-if="!loading && hasData">
      <div ref="caloriesChartRef" class="chart calories-chart"></div>
      <div class="nutrition-grid">
        <div ref="proteinChartRef" class="chart macro-chart"></div>
        <div ref="fatChartRef" class="chart macro-chart"></div>
        <div ref="carbsChartRef" class="chart macro-chart"></div>
        <div ref="fiberChartRef" class="chart macro-chart"></div>
      </div>
    </div>

    <div class="empty-state" v-if="!loading && !hasData">
      <van-empty description="暂无营养数据" />
      <p class="empty-tip">记录您的饮食习惯，开始跟踪营养摄入</p>
    </div>

    <div class="loading-state" v-if="loading">
      <van-loading color="#1989fa" />
      <p>加载中...</p>
    </div>

    <div class="nutrition-summary" v-if="!loading && hasData">
      <div class="summary-title">营养摄入摘要</div>
      <div class="summary-grid">
        <div class="summary-item">
          <div class="item-value">
            {{ nutritionSummary.avgCalories }} <span class="unit">kcal</span>
          </div>
          <div class="item-label">平均热量</div>
        </div>
        <div class="summary-item">
          <div class="item-value">
            {{ nutritionSummary.avgProtein }} <span class="unit">g</span>
          </div>
          <div class="item-label">平均蛋白质</div>
        </div>
        <div class="summary-item">
          <div class="item-value">
            {{ nutritionSummary.avgFat }} <span class="unit">g</span>
          </div>
          <div class="item-label">平均脂肪</div>
        </div>
        <div class="summary-item">
          <div class="item-value">
            {{ nutritionSummary.avgCarbs }} <span class="unit">g</span>
          </div>
          <div class="item-label">平均碳水</div>
        </div>
      </div>
    </div>

    <div class="recommendation-section" v-if="!loading && hasData">
      <div class="recommendation-title">营养建议</div>
      <div class="recommendation-content">
        <p>{{ nutritionRecommendation }}</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from "vue";
import { useUserStore } from "../../stores/userStore";
import { getUserNutritionStats, getUserHealth } from "../../api/user";
import { showToast } from "vant";
import * as echarts from "echarts/core";
import { BarChart, LineChart, PieChart } from "echarts/charts";
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
} from "echarts/components";
import { CanvasRenderer } from "echarts/renderers";

// 注册必要的组件
echarts.use([
  BarChart,
  LineChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  CanvasRenderer,
]);

const userStore = useUserStore();
const userId = computed(() => userStore.userId);

// 时间范围选择
const timeRange = ref("week");
const timeRangeOptions = [
  { text: "最近7天", value: "week" },
  { text: "最近30天", value: "month" },
  { text: "最近3个月", value: "quarter" },
];

// 图表引用
const caloriesChartRef = ref(null);
const proteinChartRef = ref(null);
const fatChartRef = ref(null);
const carbsChartRef = ref(null);
const fiberChartRef = ref(null);

// 图表实例
let caloriesChart = null;
let proteinChart = null;
let fatChart = null;
let carbsChart = null;
let fiberChart = null;

// 数据状态
const loading = ref(true);
const nutritionData = ref(null);
const userHealth = ref(null);
const hasData = computed(
  () =>
    nutritionData.value &&
    nutritionData.value.dates &&
    nutritionData.value.dates.length > 0
);

// 营养摘要数据
const nutritionSummary = ref({
  avgCalories: 0,
  avgProtein: 0,
  avgFat: 0,
  avgCarbs: 0,
});

// 营养建议
const nutritionRecommendation = computed(() => {
  if (!hasData.value || !userHealth.value)
    return "请先完善您的健康信息，以获取个性化营养建议。";

  let recommendation = "基于您的饮食记录，我们建议：";
  const summary = nutritionSummary.value;
  const health = userHealth.value;

  // 卡路里建议
  if (health.calorie_needs && summary.avgCalories) {
    const calorieRatio = summary.avgCalories / health.calorie_needs;
    if (calorieRatio < 0.8) {
      recommendation += "增加适量的总热量摄入，目前低于您的需求。";
    } else if (calorieRatio > 1.2) {
      recommendation += "适当控制总热量摄入，目前超过您的需求。";
    } else {
      recommendation += "您的热量摄入较为合理，请继续保持。";
    }
  }

  // 蛋白质建议
  if (health.protein_needs && summary.avgProtein) {
    if (summary.avgProtein < health.protein_needs * 0.8) {
      recommendation += "增加优质蛋白质的摄入，如瘦肉、蛋、豆制品等。";
    }
  }

  return recommendation;
});

// 监听时间范围变化
watch(timeRange, () => {
  loading.value = true;
  loadNutritionData();
});

// 加载营养数据
const loadNutritionData = async () => {
  try {
    // 设置时间范围参数
    let days = 7;
    if (timeRange.value === "month") days = 30;
    if (timeRange.value === "quarter") days = 90;

    const [nutritionRes, healthRes] = await Promise.all([
      getUserNutritionStats(userId.value, { days }),
      getUserHealth(userId.value),
    ]);

    if (nutritionRes.code === 200 && nutritionRes.data) {
      nutritionData.value = nutritionRes.data;

      // 计算平均值
      const calcAvg = (arr) =>
        arr.length ? arr.reduce((sum, val) => sum + val, 0) / arr.length : 0;
      nutritionSummary.value = {
        avgCalories: calcAvg(nutritionData.value.calories || []).toFixed(0),
        avgProtein: calcAvg(nutritionData.value.protein || []).toFixed(1),
        avgFat: calcAvg(nutritionData.value.fat || []).toFixed(1),
        avgCarbs: calcAvg(nutritionData.value.carbs || []).toFixed(1),
      };

      // 渲染图表
      renderCharts();
    } else {
      nutritionData.value = null;
    }

    if (healthRes.code === 200 && healthRes.data) {
      userHealth.value = healthRes.data;
    }
  } catch (error) {
    console.error("获取营养数据失败", error);
    showToast("获取营养数据失败");
    nutritionData.value = null;
  } finally {
    loading.value = false;
  }
};

// 渲染图表
const renderCharts = () => {
  if (!hasData.value) return;

  // 热量图表 - 折线图
  if (caloriesChartRef.value) {
    if (!caloriesChart) {
      caloriesChart = echarts.init(caloriesChartRef.value);
    }
    const option = {
      title: {
        text: "热量摄入趋势",
        left: "center",
        textStyle: {
          fontSize: 14,
        },
      },
      tooltip: {
        trigger: "axis",
      },
      xAxis: {
        type: "category",
        data: nutritionData.value.dates,
        axisLabel: {
          fontSize: 10,
          formatter: (value) => value.substr(5), // 只显示月-日
        },
      },
      yAxis: {
        type: "value",
        name: "卡路里(kcal)",
        nameTextStyle: {
          fontSize: 10,
        },
        axisLabel: {
          fontSize: 10,
        },
      },
      series: [
        {
          name: "热量",
          type: "line",
          data: nutritionData.value.calories,
          smooth: true,
          markLine: userHealth.value?.calorie_needs
            ? {
                data: [
                  {
                    name: "推荐摄入量",
                    yAxis: userHealth.value.calorie_needs,
                    lineStyle: { color: "#91cc75" },
                    label: { formatter: "推荐: {c} kcal", fontSize: 10 },
                  },
                ],
              }
            : {},
        },
      ],
      grid: {
        left: "10%",
        right: "5%",
        bottom: "15%",
      },
    };
    caloriesChart.setOption(option);
  }

  // 蛋白质图表 - 柱状图
  if (proteinChartRef.value) {
    if (!proteinChart) {
      proteinChart = echarts.init(proteinChartRef.value);
    }
    const option = {
      title: {
        text: "蛋白质摄入",
        left: "center",
        textStyle: {
          fontSize: 12,
        },
      },
      tooltip: {
        trigger: "axis",
      },
      xAxis: {
        type: "category",
        data: nutritionData.value.dates.slice(-7),
        axisLabel: {
          fontSize: 8,
          formatter: (value) => value.substr(5),
        },
      },
      yAxis: {
        type: "value",
        name: "蛋白质(g)",
        nameTextStyle: {
          fontSize: 8,
        },
        axisLabel: {
          fontSize: 8,
        },
      },
      series: [
        {
          name: "蛋白质",
          type: "bar",
          data: nutritionData.value.protein?.slice(-7),
          itemStyle: {
            color: "#5470c6",
          },
        },
      ],
      grid: {
        left: "15%",
        right: "5%",
        top: "25%",
        bottom: "15%",
      },
    };
    proteinChart.setOption(option);
  }

  // 脂肪图表 - 柱状图
  if (fatChartRef.value) {
    if (!fatChart) {
      fatChart = echarts.init(fatChartRef.value);
    }
    const option = {
      title: {
        text: "脂肪摄入",
        left: "center",
        textStyle: {
          fontSize: 12,
        },
      },
      tooltip: {
        trigger: "axis",
      },
      xAxis: {
        type: "category",
        data: nutritionData.value.dates.slice(-7),
        axisLabel: {
          fontSize: 8,
          formatter: (value) => value.substr(5),
        },
      },
      yAxis: {
        type: "value",
        name: "脂肪(g)",
        nameTextStyle: {
          fontSize: 8,
        },
        axisLabel: {
          fontSize: 8,
        },
      },
      series: [
        {
          name: "脂肪",
          type: "bar",
          data: nutritionData.value.fat?.slice(-7),
          itemStyle: {
            color: "#ee6666",
          },
        },
      ],
      grid: {
        left: "15%",
        right: "5%",
        top: "25%",
        bottom: "15%",
      },
    };
    fatChart.setOption(option);
  }

  // 碳水图表 - 柱状图
  if (carbsChartRef.value) {
    if (!carbsChart) {
      carbsChart = echarts.init(carbsChartRef.value);
    }
    const option = {
      title: {
        text: "碳水摄入",
        left: "center",
        textStyle: {
          fontSize: 12,
        },
      },
      tooltip: {
        trigger: "axis",
      },
      xAxis: {
        type: "category",
        data: nutritionData.value.dates.slice(-7),
        axisLabel: {
          fontSize: 8,
          formatter: (value) => value.substr(5),
        },
      },
      yAxis: {
        type: "value",
        name: "碳水(g)",
        nameTextStyle: {
          fontSize: 8,
        },
        axisLabel: {
          fontSize: 8,
        },
      },
      series: [
        {
          name: "碳水",
          type: "bar",
          data: nutritionData.value.carbs?.slice(-7),
          itemStyle: {
            color: "#91cc75",
          },
        },
      ],
      grid: {
        left: "15%",
        right: "5%",
        top: "25%",
        bottom: "15%",
      },
    };
    carbsChart.setOption(option);
  }

  // 膳食纤维图表 - 柱状图
  if (fiberChartRef.value) {
    if (!fiberChart) {
      fiberChart = echarts.init(fiberChartRef.value);
    }
    const option = {
      title: {
        text: "膳食纤维摄入",
        left: "center",
        textStyle: {
          fontSize: 12,
        },
      },
      tooltip: {
        trigger: "axis",
      },
      xAxis: {
        type: "category",
        data: nutritionData.value.dates.slice(-7),
        axisLabel: {
          fontSize: 8,
          formatter: (value) => value.substr(5),
        },
      },
      yAxis: {
        type: "value",
        name: "膳食纤维(g)",
        nameTextStyle: {
          fontSize: 8,
        },
        axisLabel: {
          fontSize: 8,
        },
      },
      series: [
        {
          name: "膳食纤维",
          type: "bar",
          data: nutritionData.value.fiber?.slice(-7),
          itemStyle: {
            color: "#73c0de",
          },
        },
      ],
      grid: {
        left: "15%",
        right: "5%",
        top: "25%",
        bottom: "15%",
      },
    };
    fiberChart.setOption(option);
  }
};

// 窗口大小变化时重绘图表
const handleResize = () => {
  caloriesChart?.resize();
  proteinChart?.resize();
  fatChart?.resize();
  carbsChart?.resize();
  fiberChart?.resize();
};

onMounted(() => {
  loadNutritionData();
  window.addEventListener("resize", handleResize);
});

// 组件销毁时清理
const onBeforeUnmount = () => {
  window.removeEventListener("resize", handleResize);
  caloriesChart?.dispose();
  proteinChart?.dispose();
  fatChart?.dispose();
  carbsChart?.dispose();
  fiberChart?.dispose();
};
</script>

<style scoped>
.nutrition-stats-container {
  background-color: #fff;
  border-radius: 8px;
  padding: 12px;
  margin: 10px 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.stats-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.header-title {
  font-size: 16px;
  font-weight: bold;
}

.nutrition-chart-container {
  margin-top: 10px;
}

.calories-chart {
  height: 200px;
  margin-bottom: 15px;
}

.nutrition-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.macro-chart {
  height: 150px;
}

.nutrition-summary {
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #f2f2f2;
}

.summary-title {
  font-size: 15px;
  font-weight: bold;
  margin-bottom: 10px;
}

.summary-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
}

.summary-item {
  text-align: center;
}

.item-value {
  font-size: 16px;
  font-weight: bold;
  color: #1989fa;
}

.unit {
  font-size: 12px;
  color: #999;
}

.item-label {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
}

.empty-state,
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
}

.empty-tip {
  margin-top: 10px;
  color: #999;
  font-size: 13px;
}

.recommendation-section {
  margin-top: 20px;
  padding: 10px 15px;
  background-color: #f7f8fa;
  border-radius: 6px;
}

.recommendation-title {
  font-size: 15px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #333;
}

.recommendation-content {
  font-size: 13px;
  color: #666;
  line-height: 1.5;
}

@media screen and (max-width: 400px) {
  .summary-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>
